/**
 * Copyright (C) 2011 GreenSoft S.A.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ar.com.greensoft.neosystem.model.constraint;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import ar.com.greensoft.neosystem.model.references.ISO3166_2AR;

/**
 * @author Jorge E. Villaverde
 * @version 1.0.0
 * @date 21/06/2011  
 */
public class CodigoPostalArgentinoValidator implements ConstraintValidator<CodigoPostalArgentino, String>{
	private static final String INVALID_CODIGO_POSTAL_MESSAGE = "{ar.com.greensoft.neosystem.model.constraint.CodigoPostalArgentino.message}";
	
	@SuppressWarnings("unused")
	private CodigoPostalArgentino cpa;
	@Override
	public void initialize(CodigoPostalArgentino cpa) {
		this.cpa = cpa;
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if(value == null)
			return true;

		boolean isValid = false;
		
		if(value.length() == 8){
			String iso31662AR = value.substring(0, 1);			
			ISO3166_2AR codProv = ISO3166_2AR.fromCode(iso31662AR.charAt(0));
			if(codProv != null){
				String cp = value.substring(1, 5);
				try {
					Integer codPostal = Integer.parseInt(cp);
					if(codPostal > 0){
						//String calleManzana = value.substring(5, 8);
						isValid = true;
					}
				} catch (NumberFormatException e) {
				}
			}
		}

        if(!isValid){
        	context.disableDefaultConstraintViolation();
	        	context.buildConstraintViolationWithTemplate(
	        			INVALID_CODIGO_POSTAL_MESSAGE)
	        			.addConstraintViolation();	
        }
		return isValid;
	}

}
